const express = require('express')
const fs = require('fs')
const { port } = require('./config/config')
const path =require('path');
const formidableMiddleware = require('express-formidable');
// const {register} = require('./dao/emailservice')
const multer  = require('multer')
const app = express()
var bodyParser = require('body-parser')
//跨域
    app.use((req,res,next)=>{

        res.header('Access-Control-Allow-Origin', '*');
       
           res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,Authorization');
       
           res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
           next();
       })
// 处理post参数
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//静态资源访问
app.use('/static',express.static(path.join(__dirname,'public')))


require('./dao/connect')

// app.get('/email',(req,res,next)=>{
//     res.send('a')
//     register('3044596736@qq.com').then(()=>{
//         res.send('邮件发送成功')
//     }).catch((err)=>{
//         res.send('邮件发送失败')
//     })
// })
// 无权限的
app.use('/api',require('./router/index'))
// token检验
// app.use(require('./service/judge'))
//有权限的
app.use('/api',require('./router/authority'))
//测试
app.use('/test',require('./test/index'))
// 文件上传

var storage = multer.diskStorage({
    destination: async function (req, file, cb) {
      var type = file.mimetype.split('/')[0]
        try {
            await fs.accessSync(path.join(__dirname,'public',type))
        } catch (error) {
            await fs.mkdirSync(path.join(__dirname,'public',type))
        }
        try {
            await fs.accessSync(path.join(__dirname,'public',type,req.body.id))
        } catch (error) {
            await fs.mkdirSync(path.join(__dirname,'public',type,req.body.id))
        }
      cb(null,path.join(__dirname,"public",type,req.body.id))
    },
    filename: function (req, file, cb) {
        var arr = file.originalname.split('.')
        var suffix = arr[arr.length-1]
        var num = Math.ceil(Math.random()*10000)
      cb(null,num + Date.now()+ '.'+suffix)
    }
  })
var upload = multer({storage})
app.options('/files/upload',(req,res,next)=>{
    res.send('ok')
})
app.post('/files/upload',upload.array('file'),function(req,res,next){
    var id = req.body.id
    if(req.files.length==1){
        var type = req.files[0].mimetype.split('/')[0]
        var data ='http://localhost:3000/static/'+type+'/'+req.body.id+"/"+req.files[0].filename;
    }else{
        var data =[]
        req.files.forEach(item=>{
        var type = item.mimetype.split('/')[0]
            data.push(`http://localhost:3000/static/${type}/${req.body.id}/${item.filename}`)
        })
    }
   res.send(data)
})
app.options('*',(req,res,next)=>{
    res.send('ok')
})
//404处理
app.use((req, res) => {
    res.status(404).send('not found')
})

//错误处理
app.use((req, res,err) => {
    res.status(err.status||500).send(err.message)
})
app.listen(port, () => {
    console.log('服务器已启动');
})